<template>
  <el-table ref="table" @current-change="changeCurrentRow" :highlight-current-row="isPicker && !isMultiplePicker" @row-dblclick="dbclickRow" @sort-change="changeSort" :border="isShowBorder" :data="gridData"  class="datagrid-table" :row-class-name="tableRowClass" :height="tableHeight" v-loading="tableLoading">
    <el-table-column type="selection" width="55" :selectable="selectable" fixed="left" v-if="!isPicker || (isPicker && isMultiplePicker)"></el-table-column>
    <el-table-column type="index" width="50" label="序号" fixed="left"></el-table-column>
    <el-table-column v-for="item in tableField" :key="item.field" :sortable="item.sortable ? item.sortable :false" :prop="item.field" :fixed="item.fixed ? item.fixed : false" :label="item.tableLabel ? item.tableLabel : item.label" :width="item.width" :min-width="item.minWidth" :formatter="item.formatter">
      <template slot-scope="scope">
        <el-switch
          v-if="item.tableType == 'switch'"
          v-model="scope.row[item.field]"
          @change="(e)=>changeTableSwitch(item,scope.row,e)"
          :active-value="1"
          :inactive-value="0"
          :active-text="item.tableSwitchOptions[1].label"
          :inactive-text="item.tableSwitchOptions[0].label">
        </el-switch>
        <template v-if="item.tableType == 'tagIds'">
          <el-tag class="datagrid-table-tags" v-for="tag in scope.row[item.field + '_arr']" :key="tag.value" disable-transitions>{{tag.label}}</el-tag>
        </template>
        <template v-if="item.tableType == 'tags'">
          <el-tag class="datagrid-table-tags" v-for="tag in scope.row[item.field]" :key="tag" disable-transitions>{{tag}}</el-tag>
        </template>
        <template v-if="item.tableType == 'tag'">
          <el-tag class="datagrid-table-tags" :type="item.tableTagObject[scope.row[item.field]] && item.tableTagObject[scope.row[item.field]].type ? item.tableTagObject[scope.row[item.field]].type : ''" disable-transitions>{{item.tableTagObject[scope.row[item.field]] ? item.tableTagObject[scope.row[item.field]].label : ''}}</el-tag>
        </template>
        <div v-if="item.tableType == 'tagcolor'" class="tagcolor">
          <div class="tagcolor-value" v-for="tagcolorItem in scope.row[item.field+'_arr']" :key="tagcolorItem.value" :style="{color:tagcolorItem.color_text? tagcolorItem.color_text:'#409eff',background:tagcolorItem.color_bg ? tagcolorItem.color_bg:'#ecf5ff','border-color':tagcolorItem.color_border ? tagcolorItem.color_border:'#d9ecff'}">{{tagcolorItem['label']}}</div>
        </div>
        <template v-if="item.tableType == 'object'">{{item.tableObject[scope.row[ item.tableAlias ? item.tableAlias : item.field]]}}</template>
        <template v-if="item.tableType == 'cover'">
          <el-image class="datagrid-table-cover" :preview-src-list="[scope.row[item.tableAlias ? item.tableAlias : item.field]]" fit="cover" :src="scope.row[item.tableAlias ? item.tableAlias : item.field]"></el-image>
        </template>
        <template v-if="!item.tableType">{{scope.row[item.tableAlias ? item.tableAlias : item.field]}}</template>
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="150" v-if="!isPicker && (Object.keys(gridDo).length > 0 || custButton.length > 0)">
      <template slot-scope="scope">
        <el-button type="text" v-if="gridDo.look">详情</el-button>
        <el-button type="text" v-if="gridDo.edit" @click="tapEdit(scope.row)">编辑</el-button>
        <el-button type="text" v-if="gridDo.delete" @click="tapDel(scope.row)">删除</el-button>
        <template v-for="custBtn in gridDo.customize" >
          <el-button type="text" v-if="isShowCustBtn(custBtn,scope.row)" @click="tapCustBtn(custBtn.callback,scope.row)" :key="custBtn.button">{{custBtn.button}}</el-button>
        </template>
        <template v-if ="isShowCustDrop(scope.row)">
          <el-dropdown @command="tapCustCommand">
            <span class="el-dropdown-link">
              <el-button type="text">操作</el-button><i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <template v-for="custBtn in custButton">
                <el-dropdown-item v-if="isShowCustBtn(custBtn,scope.row)" :command="setDropdownCommand(custBtn,scope.row)" :key="custBtn.button" >{{custBtn.button}}</el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
        <template v-else>
          <template v-for="custBtn in custButton" >
            <el-button type="text" v-if="isShowCustBtn(custBtn,scope.row)" @click="tapCustButton(custBtn,scope.row)" :key="custBtn.button">{{custBtn.button}}</el-button>
          </template>
        </template>
        
        
      </template>
    </el-table-column>
  </el-table>
</template>
<style lang="less" scoped>
  /deep/.el-table-column--selection .cell{padding-left:10px;}
  .el-table .warning-row {
    background: oldlace;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    margin-left:10px;
  }
  .datagrid-table-tags{margin:5px;}
  .datagrid-table-cover{width: 66px; height: 66px;}
  .tagcolor{display: flex;flex-wrap: wrap;align-items: center;}
  .tagcolor-value{border:1px solid #ccc;display: flex;justify-content: center;align-items: center;border-radius: 4px;margin-bottom:10px;height:32px;padding:0 20px;margin:0 10px 10px 0;}

</style>
<script>
import {checkCondition} from '@/utils';
export default {
  created(){
    this.setTableField();
    this.showGridDo = JSON.stringify(this.gridDo) === '{}' ? false : true;
    /*
    let tableField = this.gridField.sort(function(a,b){
      if (!a.tableIndex) return true;
      if (!b.tableIndex) return false;
      return a.tableIndex - b.tableIndex;
    });
    tableField.forEach(item=>{
      if (item.type == 'select') item.formatter = function( row, column, cellValue, index ){
        return 11;
      }
    });
    this.tableField = fieldArr;
    */
  },
  mounted(){
    
    let topPadding = 80;
    if (this.isTabPane) topPadding += 150;
    this.$nextTick(function () {
      if (this.isPicker) {
        this.tableHeight = 450;
        return;
      }
      this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - topPadding;
      
      // 监听窗口大小变化
      let self = this;
      window.onresize = function() {
          self.tableHeight = window.innerHeight - self.$refs.table.$el.offsetTop - topPadding;
      }
    })
  },
  props:{
    isPicker:{
      type:Boolean,
      default(){
        return false;
      }
    },
    isMultiplePicker:{
      type:Boolean,
      default(){
        return false;
      }
    },
    isTabPane:{
      type:Boolean,
      default(){
        return false;
      }
    },
    custButton:{
      type:Array,
      default(){
        return []
      }
    },
    gridData:{
      type:Array,
      default() {
        return []
      }
    },
    gridField:{
      type:Array,
      default(){
        return []
      }
    },
    gridName:{
      type:String,
      default(){
        return '';
      }
    },
    gridDo:{
      type:Object,
      default(){
        return {};
      }
    },
    rowClass:{
      type:String,
      default(){
        return ''
      }
    },
    controller:{
      type:String,
      default(){
        return '';
      }
    }
  },
  data(){
    return {
      tableLoading:false,
      tableHeight:'100%',
      tableField:[],
      showGridDo:false,
      isShowBorder:false,
      currentRow:{}
    }
  },
  methods:{
    changeCurrentRow(newRow,oldRow){
      this.currentRow = newRow;
    },
    getCurrentRow(){
      return this.currentRow;
    },
    dbclickRow(row, column, cell, e){
      if (this.isPicker) {
        this.$emit('dbclickRow',row,column,cell,e);
      }

    },
    changeTableSwitch(params,row,v){
      let newVal = v;
      let oldVal = v == 1 ? 0 : 1;
      row[params.field] = oldVal;
      this.$tool.confirm('您确认要进行这个操作嘛？').then(confirmRes=>{
        let data = {id:row.id};
        data[params.field] = newVal;
        this.$request({c:params.tableSwitchAction,data,loading:'正在处理……'}).then(res=>{
          this.$emit('reloadPage');
        });
        
      }).catch(()=>{

      });
    },
    changeSort({prop,order,column}){
      for (let index in this.tableField){
        if (this.tableField[index].field == column.property){
          if (this.tableField[index].sortAlias) prop = this.tableField[index].sortAlias
          break;
        }
      }
      let searchData = [];
      if (order == 'ascending') {
        searchData.push({field:prop,order:'ASC'});
      } else if (order == 'descending') {
        searchData.push({field:prop,order:'DESC'});
      }
      this.$emit('changeSort',searchData);
    },
    selectable(row,index){
      return row.selectable === false ?  false : true;
    },
    tapCustBtn(callbackEvent,row){
      this.$emit('tapCustBtn',callbackEvent,row);
    },
    setDropdownCommand(custButton,row){
      return {
        custButton:custButton,
        row:row
      }
    },
    tapCustCommand({custButton,row}){
      this.tapCustButton(custButton,row);
    },
    tapCustButton(custButton,row){
      this.$emit('tapCustButton',custButton.button,row);
    },
    tableRowClass({row,rowIndex}){
      if (this.rowClass == 'checkHigh'){
         return row.check_state == 0 ? 'warning-row' : '';
      }
      return '';
    },
    tapEdit(row){
      this.$emit('tapEdit',row);
    },
    tapDel(row){
      this.$emit('tapDel',row)
    },
    showLoading(){
      this.tableLoading = true;
    },
    hideLoading(){
      this.tableLoading = false;
    },
    getSelection(){
       return this.$refs.table.selection;
    },
    getColumns(){
      return this.$refs.table.columns;
    },
    setBorderShow(isShow){
      this.isShowBorder = isShow;
    },
    setTableField(){
      let tableFields = this.$store.getters.userSetting.datagridTable && this.$store.getters.userSetting.datagridTable[this.gridName] ? this.$store.getters.userSetting.datagridTable[this.gridName] : {};
      let fieldArr = [];
      let ascFieldArr = [];
      let descFieldArr = [];
      this.gridField.forEach(item=>{
        let field = {...item};
        if (tableFields[item.field] && tableFields[item.field].tableIndex >= 0) field.tableIndex = tableFields[item.field].tableIndex;
        if (tableFields[item.field] && tableFields[item.field].width) field.width = tableFields[item.field].width;
        if (tableFields[item.field] && tableFields[item.field].minWidth) field.minWidth = tableFields[item.field].minWidth;
        if (field.isTable && (!tableFields[field.field] ||  tableFields[item.field].isTable !== false)) {
          if (field.tableIndex < 0) {
            descFieldArr.push(field);
          } else {
            ascFieldArr.push(field);
          }
        }

      });
      ascFieldArr.sort(function(a,b){
        a.tableIndex = a.tableIndex ? a.tableIndex : 9999999999;
        b.tableIndex = b.tableIndex ? b.tableIndex : 9999999999;
        return a.tableIndex - b.tableIndex;
      });
      descFieldArr.sort(function(a,b){
        a.tableIndex = a.tableIndex ? a.tableIndex * -1 : 9999999999;
        b.tableIndex = b.tableIndex ? b.tableIndex * -1 : 9999999999;
        return  b.tableIndex - a.tableIndex;
      });
      this.tableField = [];
      ascFieldArr.forEach(item=>{
        fieldArr.push(item);
      })
      descFieldArr.forEach(item=>{
        fieldArr.push(item);
      })
      this.tableField = [];
      this.$nextTick(()=>{
        this.tableField = fieldArr;
      });
    },
    isShowCustBtn(custBtn,row){
      return custBtn.condition ? checkCondition(row,custBtn.condition) : true;
    },
    isShowCustDrop(row){
      let num = 0;
      this.custButton.forEach(custBtn=>{
        if (!custBtn.condition || checkCondition(row,custBtn.condition)) num++;
      })
      return num > 1 ? true : false;
    }
  },
  computed:{

  }
}

</script>